﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Hxsoft.AppV1.Module;

namespace Hxsoft.AppV1.Admin.DictionaryManage
{
	public partial class AddDictionary : BasePage
	{
		private LoadedValue<string> loadedClassCode;
		public string ClassCode
		{
			get {
				if (loadedClassCode.Loader == null)
					loadedClassCode.Loader = () => Request.QueryString["ClassCode"];
				return loadedClassCode.Value; 
			}
		}
		/// <summary>
		/// 字典所属的类别
		/// </summary>
		protected int ClassID
		{
			get
			{
				var id=IntExtensions.ParseOrNull(Request.QueryString["ClassID"]);
				if (!id.HasValue)
					id = DicClasses.GetIdentifier(SiteId, ClassCode);
				return id.Value;
			}
		}
        private LoadedValue<string> loadedItemClassName;
        protected string ItemClassName
        {
            get {
                if(loadedItemClassName.Loader==null)
                    loadedItemClassName.Loader=()=> DicClasses.GetItem(ClassID).ClassName;
                return loadedItemClassName.Value;
            }
        }

		/// <summary>
		/// 上级字典的标识
		/// </summary>
		protected int? PDicID
		{
			get
			{
				if (!string.IsNullOrEmpty(Request.QueryString["PDicID"]))
					return Convert.ToInt32(Request.QueryString["PDicID"]);
				return null;
			}
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			if (RightValidate())
			{
				if (!IsPostBack)
				{
					Page.DataBind();
					if (!string.IsNullOrEmpty(ClassCode))
					{
						UCAddDictionary.IsHiddenControl = !string.IsNullOrEmpty(ClassCode);
						var currentId =Dictionaries.GetCurrentIdentifier(ClassID);
                        UCAddDictionary.DicID = currentId;
                        UCAddDictionary.DicCode = currentId.ToString();
					}
				}
			}
		}

		protected void BtSubmit_Click(object sender, EventArgs e)
		{
			if (RightValidate() && IsValid)
			{
				Dictionary info = UCAddDictionary.Info;
				info.ClassId = ClassID;
				info.PDicId = PDicID;

				Dictionaries.Insert(info);
				InsertComplete();
			}
		}

		/// <summary>
		/// 返回权限验证结果，如果验证失败则显示消息提示。
		/// </summary>
		/// <returns>布尔值代表权限验证是否通过。</returns>
		public bool RightValidate()
		{
			bool right = Dictionaries.GetInsertRight(new Dictionary { ClassId = ClassID });
			if (!right)
			{
				Messages.Add(new PageMessage(false, null, PageMessageType.Error, Res.PermissionExceptionMessageTitle, Res.PermissionExceptionMessage));
			}
			return right;
		}

		/// <summary>
		/// 插入操作完成，显示消息提示。
		/// </summary>
		public void InsertComplete()
		{
			Messages.Add(new PageMessage(true, null, PageMessageType.Prompt, Res.OperationCompleteTitle, Res.OperationComplete_Insert));
		}
	}
}
